<template>
  <basic-container>
    <el-form ref="form" searchform :model="form" label-width="80px" @submit.native.prevent>
    <el-row>
      <el-col :span="5" style="min-width:211px">
        <div class="text">类型:</div>
        <el-select v-model="form.type" clearable size="mini" placeholder="请选择类型" style="width: 150px"
                   ref="originType" @visible-change="isShowSelectOptions" @change="searchCondition">
          <el-option key="" label="全部" value=""> </el-option>
          <el-option
            v-for="item in dataType"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="5" style="min-width:211px">
        <div class="text">标签:</div>
        <el-input
          id="id-offer-origincreative-searchCondition"
          size="mini"
          placeholder="请输入标签"
          v-model="form.tag"
          clearable style="width: 150px" @keyup.enter.native="searchCondition" @change="searchCondition">
        </el-input>
      </el-col>
      <el-col :span="5" style="min-width:221px">
        <div class="text">创建者:</div>
        <el-select id="id-offer-origincreative-isShowSelectOptions"
                   v-model="form.createUser" filterable clearable size="mini" placeholder="请选择创建者" style="width: 150px"
                   ref="originCreateUser" @visible-change="isShowSelectOptions" @change="searchCondition">
          <el-option key="" label="全部" value=""> </el-option>
          <el-option v-for="(item,index) in allUserList" :key="index" :label="item.realName" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col span="4" style="min-width: 240px;margin-top: -6px;">
        <el-tooltip class="item" effect="dark" content="清空" placement="top">
          <el-button id="id-offer-origincreative-button-searchCondition" type="primary" icon="el-icon-search" size="small" @click="emptyForm" style="margin-right: 0">清空</el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="搜索" placement="top">
          <el-button id="id-offer-origincreative-button-small" type="primary" icon="el-icon-search" size="small" @click="searchCondition" style="margin-right: 0">搜索</el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    </el-form>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="link" slot-scope="{row}">
        <div>
          <div v-if="row.link === '-2'">上传失败</div>
          <div v-else>{{ row.link }}</div>
        </div>
      </template>
      <template slot="thumbnailUrl" slot-scope="{row}">
        <div>
          <div v-if="row.thumbnailUrl === '-2'">上传失败</div>
          <div v-if="row.thumbnailUrl === '-1'">上传中</div>
          <img v-if="row.thumbnailUrl !== '-1'"
               style="max-width: 100%;width: auto;max-height: 200px;height: auto"
               :src="row.thumbnailUrl" alt="" @click="getUrl(row)">
        </div>
      </template>
      <template slot="menuLeft">
        <el-button id="id-offer-origincreative-button-handleAdd"
                   type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   @click="handleAdd">新 增
        </el-button>
        <el-button id="id-offer-origincreative-button-handleDelete"
                   type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.creative_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>

    <!--新增弹窗-->
    <div v-if="dialogVisible">
      <el-dialog :title="title" :visible.sync="dialogVisible" :modal-append-to-body="false"
                 :close-on-click-modal="false" :before-close="handleClose" :append-to-body="true" width="70%">
        <el-form label-position="right" label-width="80px" ref="submitForm" :model="submitForm"  v-loading="formLoading"
                 element-loading-spinner="null"
                 element-loading-background="rgba(255, 255, 255, 0.6)">
          <el-row style="display: flex;flex-wrap: wrap">
            <el-col style="width: 46%">
              <el-form-item label="标签" prop="tag">
                <el-select id="id-offer-origincreative-tag"
                           v-model="submitForm.tag" size="mini" multiple filterable allow-create default-first-option
                           class="form_item">
                  <el-option v-for="(item,index) in tagsList" :key="index" :label="item" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="备注" prop="remark">
                <el-input id="id-offer-origincreative-remark" v-model="submitForm.remark" style="width: 50%" type="textarea" size="mini"
                          :autosize="{minRows:2}">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="素材">
              <upload-obs :fileList="fileList" :limit="100"
                          ref="beeltesUpload"></upload-obs>
            </el-form-item>
          </el-row>
          <el-form-item>
            <el-button id="id-offer-origincreative-rowSave"
                       size="small" icon="el-icon-circle-plus-outline" type="primary"
                       style="margin-left: 60%;margin-top: 30px;"
                       @click="rowSave">提 交
            </el-button>
            <el-button id="id-offer-origincreative-handleClose"
                       size="small" icon="el-icon-circle-close" @click="handleClose">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
<!--视频图片弹窗-->
    <creative-card-preview v-model="dialogFormVisible" :media-preview="currentCreative"></creative-card-preview>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove ,getTagList} from "@/api/offer/origincreative";
import {getAllUser} from "@/api/user"
import {mapGetters} from "vuex";
import uploadObs from "@/components/beetles-upload/upload_obs";
import { createWebSocket } from "@/util/ws";
import CreativeCardPreview from "@/components/CreativeCardPreview/CreativeCardPreview";

const tagsSearchList = []
export default {
  components: {
    uploadObs,
    CreativeCardPreview
  },
  data() {
    return {
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      type: '',
      thumbnailVoUrlList:'',
      thumbnailUrlList: '',
      dialogFormVisible:false,
      tagsList: [{label:1,value:1}],  //标签列表
      allUserList: [],
      title: '',//标题
      dialogVisible: false,
      form: {
        createUser: '',
        type: '',
        tag: '',
      },
      fileList: [],
      submitForm: {
        tag: [],
        remark: ''
      },
      query: {},
      loading: false,
      formLoading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      dataType: [{
        value: '0',
        label: '图片'
      }, {
        value: '1',
        label: '视频'
      }],
      option: {
        addBtn: false,
        delBtn: true,
        menuWidth: 100,
        // height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        excelBtn: true,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: "名称",
            prop: "name",
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur"
            }]
          },
          {
            label: "类型",
            prop: "type",
            dicData: [
              {label: '图片', value: 0},
              {label: '视频', value: 1},
            ],
            addDisplay: false,
          },
          // {
          //   label: "素材链接",
          //   prop: "link",
          //   rules: [{
          //     required: true,
          //     message: "请输入素材链接",
          //     trigger: "blur"
          //   }],
          //   slot: true,
          // },
          {
            label: "标签",
            prop: "tag",
            type: 'select',
            dicData:tagsSearchList,
          },
          {
            label: '创建人',
            prop: 'username',
          }, {
            label: '创建时间',
            prop: 'createTime',
          },
          {
            label: '素材',
            prop: 'thumbnailUrl',
            slot: true,
          }

        ]
      },
      data: [],
      // marco
      // 当前素材
      currentCreative:null
    };
  },
  created() {
    //window.addEventListener('keyup', this.searchCondition) //监听键盘事件
    getAllUser().then(res =>{
      this.allUserList = res.data.data
    })
    //获取tag列表
    getTagList().then(res=>{
      this.tagsList = res.data.data
      this.tagsList.map(item =>{
        tagsSearchList.push({label:item,value:item})
      })
    })
  },
  mounted() {
    let self = this;
    self.isRefreshing = false;
    if(!self.socket) {
      self.socket = createWebSocket('/api/blade-system/wss','json');
      if(self.socket) self.socket.ontextmessage = (msg)=>{
        let msgObj = JSON.parse(msg);
        //console.log("socket receive:" + msg)
        if(msgObj) {
          if(!self.isRefreshing && msgObj.messageName === 'tenantMessage' && msgObj.data.messageName=== 'originCreativeChanged') {
            if(msgObj.data.originCreativeIds != null) {
              let originCreativeIdList = msgObj.data.originCreativeIds.split(",");
              if(self.data.find((v)=>{return originCreativeIdList.includes(v.id);}) == null) {
                return;
              }
            }
            self.isRefreshing = true;
            //不可以频繁刷新，如果有刷新需求，延迟5秒刷新，在延迟期间，有新的刷新需求均不会多次触发onLoad
            setTimeout(() => {
              self.onLoad(self.page);
              self.isRefreshing = false;
            },5000);
          }
        }
      };
      if(self.socket) self.socket.onerror = ()=>{
        this.$message({
          type: 'warning',
          message: '您的网络目前不稳定，数据可能不能自动刷新！'
        });
      };
    }
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if(self.socket) {
      self.socket.close();
      self.socket = null;
    }

    next();
  },
  computed: {
    ...mapGetters(["permission"]),
    ...mapGetters(["userInfo","token"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.origincreative_add, false),
        viewBtn: this.vaildData(this.permission.origincreative_view, false),
        delBtn: this.vaildData(this.permission.origincreative_delete, false),
        editBtn: this.vaildData(this.permission.origincreative_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    isShowSelectOptions(isShowSelectOptions){
      if(!isShowSelectOptions) this.$refs.originType.blur();
      if(!isShowSelectOptions) this.$refs.originCreateUser.blur();
    },
    //搜索按钮函数
    searchCondition(){
      this.query = this.form;
      this.page.currentPage = 1;
      this.onLoad(this.page,this.form)
    },
    //清空按钮函数
    emptyForm(){
      this.form = {
        createUser: '',
        type: '',
        tag: ''
      }
      this.query = this.form
      this.onLoad(this.page,this.form)
    },
    getUrl(row) {
      console.log(row)
      // this.type = type
      // this.thumbnailUrlList = link
      this.currentCreative = row
      this.dialogFormVisible = true
    },
    previewStyle() {
      // let height = ((window.innerHeight < 300) ? 300 : (window.innerHeight - 160));
      return {
        maxWidth: '100%',
        /*height: height + 'px'*/
      };
    },
    handleAdd() {
      this.title = "新增"
      getTagList().then(res=>{
        this.tagsList = res.data.data
        this.tagsList.map(item =>{
          tagsSearchList.push({label:item,value:item})
        })
      })
      this.dialogVisible = true
    },
    //关闭弹窗
    handleClose() {
      // this.$nextTick(()=>{
      //   this.$refs['form'].resetFields();//清空表单
      // })
      this.$refs.submitForm.resetFields()
      this.$refs.beeltesUpload.$refs.upload.uploadFiles = []
      this.dialogVisible = false
    },
    //校验华为云素材
    verificationFiles() {
      let files = this.$refs.beeltesUpload.$data.fileMap
      if (files.length === 0) {
        this.$message({
          type: 'error',
          message: '请提供上传素材!'
        })
        return null
      }

      let complete = true // 完成度
      files.map(item => {
        if (item.progress !== 100) {
          complete = false
        }
      })

      if (!complete) {
        this.$message({
          type: 'error',
          message: '请等待素材上传完成!'
        })
        return null
      }
      let val = []
      files.map(item => {
        val.push({
          name: item.name,
          url: item.url,
        });
      });
      return val
    },
    async rowSave() {
      let files = this.verificationFiles();
      if (files === null)
        return;
      if(!this.$refs.beeltesUpload.uploadCompleted()) {
        this.$message.warning('文件未上传完成');
        return;
      }
      let form = {
        remark: this.submitForm.remark,
        tag: this.submitForm.tag.join(','),
        fileMapList: files,
      };

      this.formLoading = true
      add(form).then(res=>{
        if(res.data.success) {
          this.$message.success('提交成功');
          this.handleClose()
          this.onLoad(this.page)
        }
      }).finally(()=>{
        this.formLoading = false
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.selectionClear();
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.selectionClear();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.selectionClear();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
      this.selectionClear();
    },
    onLoad(page, params = {}) {
      // this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        for (let i = 0; i < data.records.length; i++) {
          if (data.records[i].link === '-2') {
            data.records[i].thumbnailUrl = '-2'
          }
        }
        this.page.total = data.total;
        this.data = data.records;
        // let refresh = false
        // this.data.map(item => {
        //   if (item.thumbnailUrl === '-1') {
        //     refresh = true
        //   }
        // })
      });
    }
  }
};
</script>
<style lang="scss" scoped>
  .text{
    width: 45px;
    height:30px;
    float: left;
    font-size: 13px;
    margin-top: 3px;
    color: #72767b
  }
  .search-circle{
    border-radius: 50%;
    border: 1px solid #dcdfe6;
    width: 30px;
    height: 30px;
    padding: 0;
    margin-right: 0;
  }
</style>
